package com.github.freewu.commons.db;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.github.freewu.commons.utils.ToastUtil;

import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.internal.DaoConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okio.BufferedSource;
import okio.Okio;

/**
 * 数据库操作工具类
 * Created by free on 16-9-19.
 */
public class DBUtils {
    private static List<DbInfo> dbInfoList=new ArrayList<>(5);

    private static Context context;

    private static DBHelper dbHelper;

    private static DBUtils dbUtils;

    public static void init(Context context) {
        DBUtils.context = context;
    }

    public static void addDBInfo(DbInfo dbInfo) {
        DBUtils.dbInfoList.add(dbInfo);
    }

    public static synchronized DBUtils getInstance(String DBName) {
        for (DbInfo dbInfo : dbInfoList) {
            if (dbInfo.getDbName().equals(DBName)) {
                dbHelper = new DBHelper(context,dbInfo.getDbName(),dbInfo.getVersion(),dbInfo.getSqlPath());
            }
        }

        dbUtils = new DBUtils();

        return dbUtils;
    }

    public Database getDateBase(boolean isWrite) {
        if (isWrite) {
            return dbHelper.getWritableDb();
        } else {
            return dbHelper.getReadableDb();
        }
    }

    public Database getDateBase() {
        return getDateBase(true);
    }

    /**
     * 设置数据库升级接口
     *
     * @param onUpdateDbListener
     */
    public void setOnUpdateDbListener(OnUpdateDbListener onUpdateDbListener) {
        if (dbHelper != null) {
            dbHelper.setDbListener(onUpdateDbListener);
        }
    }
}
